package com.yuantu.judiciary.dao;

import com.yuantu.judiciary.model.domain.SmsRecordDO;
import com.yuantu.judiciary.model.enums.SmsTemplateType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

/**
 * 短信记录数据库操作接口
 *
 * @author syw
 * @since 2023-06-08
 **/
public interface ISmsRecordDao extends JpaRepository<SmsRecordDO, Long> {

    /**
     * 根据消息类型和备注获取短信内容
     *
     * @param type    .
     * @param remarks .
     * @return .
     */
    SmsRecordDO findByTypeAndRemarksAndDeletedFalse(SmsTemplateType type, String remarks);

    SmsRecordDO findByRemarksAndDeletedFalse(String remarks);

    /**
     * 根据手机号和消息类型获取有效短信内容
     *
     * @param phone .
     * @param type  .
     * @return .
     */
    List<SmsRecordDO> findByPhoneAndTypeAndDeletedFalse(String phone, SmsTemplateType type);

    List<SmsRecordDO> findByPhoneAndTypeAndContentAndDeletedFalse(String phone, SmsTemplateType type, String content);

    /**
     * 失效相同手机号、类型数据
     *
     * @param phone .
     * @param type  .
     */
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query("update SmsRecordDO set deleted = true where phone = :phone and type = :type and deleted = false ")
    void deleteByPhoneAndType(String phone, SmsTemplateType type);

    /**
     * 通过手机号查找验证码
     *
     * @param phone       .
     * @param type        .
     * @param code        .
     * @param expiresTime .
     * @return .
     */
    SmsRecordDO findOneByPhoneAndTypeAndContentAndExpiresTimeGreaterThanEqualAndDeletedFalse(
            String phone,
            SmsTemplateType type,
            String code,
            Timestamp expiresTime
    );

    List<SmsRecordDO> findByContentAndTypeAndDeletedFalse(String content, SmsTemplateType type);
}
